<template>
    <el-card class="box-card card-item mb-5 border-1" shadow="never" :body-style="{ padding: '20px' }">
        <!-- card body -->
        <el-text class="mx-1 mr-3">文章标题</el-text>
        <el-input v-model="searchTitle" placeholder="请输入（模糊查询）" class="w-50 mr-5" />

        <el-text class="mx-1 mr-3">发布日期</el-text>
        <el-date-picker style="top: 3px" v-model="pickDate" type="daterange" range-separator="至"
            start-placeholder="开始时间" end-placeholder="结束时间" :shortcuts="shortcuts" size="default"
            @change="datepickerChange" />

        <el-button type="primary" class="ml-3" :icon="Search" @click="getTableData">查询</el-button>
        <el-button class="ml-3" :icon="RefreshRight" @click="reset">重置</el-button>
    </el-card>

    <el-card class="box-card card-item border-1" shadow="never">
        <!-- card body -->
        <!-- 新增按钮 -->
        <div>
            <el-button type="primary" @click="showArticleEditor()">
                <el-icon class="mr-1">
                    <EditPen />
                </el-icon>
                写文章</el-button>
            <el-button type="danger" @click="deleteArticleSubmit()" :disabled="!selectedRows.length">
                <el-icon class="mr-1">
                    <Delete/>
                </el-icon>
                批量删除
            </el-button>
        </div>

        <el-table :data="tableData" stripe v-loading="tableLoading" @selection-change="handleSelectionChange" class="article-table">
            <el-table-column type="selection" width="55"/>
            <el-table-column prop="articleId" label="ID" width="180"/>
            <el-table-column prop="title" label="标题" min-width="330"/>
            <el-table-column label="预览图" width="180">
                <template #default="scope">
                    <el-image style="width: 50px;" :src="scope.row.cover" />
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="发布时间" width="180" />
            <el-table-column label="操作" width="300" fixed="right">
                <template #default="scope">
                    <el-button size="small" @click="showArticleEditor(scope.row)">
                        <el-icon class="mr-1">
                            <Edit />
                        </el-icon>
                        编辑</el-button>
                    <el-button size="small" @click="previewArticle(scope.row)">
                        <el-icon class="mr-1">
                            <View />
                        </el-icon>
                        预览</el-button>
                    <el-button type="danger" size="small" @click="deleteArticleSubmit([scope.row])">
                        <el-icon class="mr-1">
                            <Delete />
                        </el-icon>
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <div class="pagination-container">
            <el-pagination v-model:current-page="current" v-model:page-size="size" :page-sizes="[10, 20, 50]"
                background="true" layout="total, sizes, prev, pager, next, jumper"
                :total="total" @size-change="handleSizeChange" @current-change="getTableData" />
        </div>
    </el-card>

    <!-- 文章编辑器 -->
    <el-dialog v-model="isArticleEditorShow" fullscreen="true" :show-close="false" :modal="false">
        <template #header="{ close, titleId, titleClass }">
            <div class="dialog-header">
                <div class="dialog-title">写文章</div>
                <div class="button-group">
                    <el-button @click="hideArticleEditor">取消</el-button>
                    <el-button type="primary" @click="handleSubmit">发布</el-button>
                </div>
            </div>
        </template>
        <el-form :model="form" ref="articleFormRef" label-position="top" :size="large" :rules="rules">
            <el-form-item label="标题" prop="title">
                <el-input v-model="form.title" autocomplete="off" size="large" maxlength="40" show-word-limit
                    clearable />
            </el-form-item>
            <el-form-item label="内容" prop="content">
                <MdEditor v-model="form.content" @onUploadImg="onUploadImg" :editorId="form.articleId ? 'updateArticleEditor' : 'publishArticleEditor'" />
            </el-form-item>
            <el-form-item label="封面" prop="cover">
                <el-upload class="avatar-uploader" action="#" :on-change="handleTitleImageChange" :auto-upload="false"
                    :show-file-list="false" :on-success="handleAvatarSuccess">
                    <img v-if="form.cover" :src="form.cover" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="摘要" prop="description">
                <el-input v-model="form.description" :rows="3" type="textarea" placeholder="请输入文章摘要" />
            </el-form-item>
            <el-form-item label="分类" prop="categoryId">
                <el-select v-model="form.categoryId" clearable placeholder="---请选择---" size="large">
                    <el-option v-for="item in categories" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="标签" prop="tags">
                <!-- 标签选择 -->
                <el-select v-model="form.tags" multiple filterable remote reserve-keyword placeholder="---请输入---"
                    remote-show-suffix :remote-method="remoteMethod" allow-create default-first-option
                    :loading="tagSelectLoading" size="large">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script setup>
// import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive } from 'vue';
// import MDEditor from '@/components/MDEditor.vue'
import { publishArticle, getArticlePageList, deleteArticle, getArticleDetail, updateArticle } from '@/api/admin/article'
import { uploadFile } from '@/api/admin/file'
import MdEditor from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
import { showMessage } from '@/composables/util'
import { useRouter } from 'vue-router'
import { getCategorySelect } from '@/api/admin/category'
import { selectTags, getTagSelect } from '@/api/admin/tag'
import moment from 'moment';
import { Search, RefreshRight } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()

const isArticleEditorShow = ref(false)
const tableLoading = ref(false)

const searchTitle = ref('')
const pickDate = ref('')
const startDate = reactive({})
const endDate = reactive({})

const selectedRows = ref([])

const handleSelectionChange = (val) => {
    selectedRows.value = val
}

const reset = () => {
    pickDate.value = ''
    startDate.value = null
    endDate.value = null
    searchTitle.value = ''
}

const resetForm = () => {
    form.articleId = null
    form.title = ''
    form.content = '请输入内容'
    form.cover = ''
    form.categoryId = null
    form.tags = []
    form.description = ''
}

const datepickerChange = (e) => {
    startDate.value = moment(e[0]).format('YYYY-MM-DD HH:mm:ss')
    endDate.value = moment(e[1]).format('YYYY-MM-DD HH:mm:ss')
}

const shortcuts = [
    {
        text: '最近一周',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            return [start, end]
        },
    },
    {
        text: '最近一个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            return [start, end]
        },
    },
    {
        text: '最近三个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            return [start, end]
        },
    },
]

const handleTitleImageChange = (file) => {
    console.log('开始上传文件')
    console.log(file)
    let formData = new FormData()
    formData.append("file", file.raw);
    uploadFile(formData).then((e) => {
        if (e.success == false) {
            let message = e.message
            showMessage(message, 'warning', 'message')
            return
        }
        form.cover = e.data.url
        showMessage('文章题图上传成功', 'success', 'message')
    })
}

const hideArticleEditor = () => {
    isArticleEditorShow.value = false
    resetForm()
}

const showArticleEditor = (row) => {
    isArticleEditorShow.value = true
    
    if (row) {
        // 编辑模式
        getArticleDetail(row.articleId).then((e) => {
            if (e.success == true) {
                form.articleId = e.data.articleId
                form.title = e.data.title
                form.content = e.data.content || '请输入内容'
                form.cover = e.data.cover
                form.categoryId = e.data.categoryId
                form.tags = e.data.tagIds || []
                form.description = e.data.description
            }
        })
    } else {
        // 新增模式
        resetForm()
    }
    
    // 加载分类和标签数据
    if (!categories.value.length) {
        getCategorySelect().then((res) => {
            categories.value = res.data || []
        })
    }
    if (!options.value.length) {
        getTagSelect().then((res) => {
            options.value = res.data || []
        })
    }
}

const onUploadImg = async (files, callback) => {
    const res = await Promise.all(
        files.map((file) => {
            return new Promise((rev, rej) => {
                console.log('==> 开始上传文件...')
                let formData = new FormData()
                formData.append("file", file);
                uploadFile(formData).then((res) => {
                    console.log(res)
                    console.log('访问路径：' + res.data.url)
                    callback([res.data.url]);
                })
            });
        })
    );
}

const previewArticle = (row) => {
    // 打开一个新页面
    let articleId = row.articleId
    let routeData = router.resolve({ path: `/article/${articleId}` });
    window.open(routeData.href, '_blank');
}

const form = reactive({
    articleId: null,
    title: '',
    content: '请输入内容',
    cover: '',
    categoryId: null,
    tags: [],
    description: ""
})

const articleFormRef = ref(null)
const rules = {
    title: [
        { required: true, message: '请输入文章标题', trigger: 'blur' },
        { min: 1, max: 40, message: '文章标题要求大于1个字符，小于40个字符', trigger: 'blur' },
    ],
    content: [{ required: true }],
    cover: [{ required: true }],
    categoryId: [{ required: true, message: '请选择文章分类', trigger: 'blur' }],
    tags: [{ required: true, message: '请选择文章标签', trigger: 'blur' }],
    description: [{ required: true, message: '请输入文章摘要', trigger: 'blur' }],
}

const tableData = ref([])
// 当前页码
const current = ref(1)
const total = ref(0)
const size = ref(10)

// 获取分页数据
function getTableData() {
    console.log('获取分页数据')
    tableLoading.value = true
    getArticlePageList({ current: current.value, size: size.value, startDate: startDate.value, endDate: endDate.value, searchTitle: searchTitle.value })
        .then((res) => {
            if (res.success == true) {
                tableData.value = res.data.records
                current.value = res.data.current
                total.value = res.data.total
                size.value = res.data.size
            }
        }).finally(() => {
            tableLoading.value = false
        })
}
getTableData()

const handleSizeChange = (e) => {
    console.log('选择的页码' + e)
    size.value = e
    getTableData()
}

const handleSubmit = () => {
    articleFormRef.value.validate((valid) => {
        if (!valid) {
            return false
        }
        
        const submitAction = form.articleId ? updateArticle : publishArticle
        
        submitAction(form).then((e) => {
            if (e.success == false) {
                showMessage(e.message, 'warning', 'message')
                return
            }

            showMessage(form.articleId ? '修改成功' : '发布成功', 'success', 'message')
            isArticleEditorShow.value = false
            resetForm()
            getTableData()
        })
    })
}

// 批量删除提交
const deleteArticleSubmit = (rows) => {
  const deleteRows = rows || selectedRows.value
  if (deleteRows.length === 0) {
    showMessage('请选择要删除的文章', 'warning')
    return
  }

  ElMessageBox.confirm(
      `是否确认要删除选中的 ${deleteRows.length} 篇文章?`,
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        const ids = deleteRows.map(row => row.articleId)
        // 修改为传递对象
        deleteArticle({data: ids}).then((e) => {
          if (e.success == true) {
            showMessage('删除成功', 'success')
            getTableData()
          } else {
            showMessage(e.message, 'warning')
          }
        })
      })
}

// 文章分类
const categories = ref([])
getCategorySelect().then((e) => {
    console.log('获取分类数据')
    console.log(e)
    categories.value = e.data
})

// 文章标签
const tagSelectLoading = ref(false)
const options = ref([])
getTagSelect().then((e) => {
    console.log('获取标签数据')
    console.log(e)
    options.value = e.data || [] // 添加默认空数组
})

const remoteMethod = (query) => {
    console.log('远程搜索')
    console.log(options.value)
    if (query) {
        tagSelectLoading.value = true
        setTimeout(() => {
            tagSelectLoading.value = false
            selectTags(query).then((e) => {
                if (e.success) {
                    options.value = e.data || [] // 添加默认空数组
                }
            })
        }, 200)
    }
}
</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
    object-fit: cover;
}

.avatar-uploader .el-upload {
    width: 178px;
    height: 178px;
    position: relative;
    cursor: pointer;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: transparent;
}

:deep(.el-upload) {
    border: none;
    padding: 0;
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
    line-height: 178px;
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
}

.el-select--large {
    width: 600px;
}

.card-item + .card-item {
  margin-top: 16px;  
}

.el-pagination {
  margin-top: 20px; 
}

.el-input {
  margin-right: 24px !important;
}

.el-date-picker {
  margin-right: 36px !important;
}

.el-text {
  margin-right: 12px !important;
}

:deep(.el-date-editor.el-input__wrapper) {
  margin-right: 36px !important;
}

/* 添加输入框焦点样式 */
:deep(.el-input__wrapper):focus-within {
    box-shadow: 0 0 0 1px var(--el-input-border-color, var(--el-border-color)) inset;
}

/* 添加上传框边框样式 */
.avatar-uploader {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    padding: 8px;
}

/* 对话框头部样式 */
.dialog-header {
    position: relative;
    display: flex;
    align-items: center;
    padding: 12px 16px;
    height: 56px;
}

.dialog-title {
    font-size: 16px;
    font-weight: 500;
    color: #333;
}

.button-group {
    position: fixed;
    top: 12px;
    right: 16px;
    z-index: 2001; /* 确保按钮在最上层 */
}

/* 调整按钮组样式 */
.button-group .el-button + .el-button {
    margin-left: 8px;
}

/* 调整按钮样式 */
:deep(.el-button) {
    padding: 8px 16px;
    font-size: 14px;
}

:deep(.el-button--primary) {
    background-color: #409eff;
}

/* 图标右边距 */
.mr-1 {
    margin-right: 4px;
}

/* 其他通用间距类 */
.mt-4 {
    margin-top: 16px;
}

.mt-5 {
    margin-top: 20px;
}

.mb-5 {
    margin-bottom: 20px;
}

.ml-3 {
    margin-left: 12px;
}

.mr-3 {
    margin-right: 12px;
}

.mr-5 {
    margin-right: 20px;
}

/* flex布局类 */
.flex {
    display: flex;
}

.items-center {
    align-items: center;
}

.justify-center {
    justify-content: center;
}

.justify-between {
    justify-content: space-between;
}

.gap-2 {
    gap: 8px;
}

/* 宽度类 */
.w-50 {
    width: 12.5rem;
}

/* 边框类 */
.border-1 {
    border-width: 1px;
}

/* 分页容器样式 */
.pagination-container {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 20px;
}

/* 表格操作按钮组 */
.table-action-group {
    display: flex;
    gap: 8px;
}

/* 卡片间距 */
.card-item + .card-item {
    margin-top: 16px;
}

/* 搜索区域样式 */
.search-area {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
}

.search-label {
    margin-right: 12px;
}

.search-input {
    margin-right: 24px;
}

/* 按钮悬停效果 */
:deep(.el-button:not(.is-disabled):hover) {
    border-color: var(--el-color-primary-light-7);
    background-color: var(--el-color-primary-light-9);
    color: var(--el-color-primary);
}

:deep(.el-button--primary:not(.is-disabled):hover) {
    border-color: var(--el-color-primary-light-3);
    background-color: var(--el-color-primary-light-3);
    color: var(--el-color-white);
}

/* 移除所有圆角 */
:deep(.el-input__wrapper),
:deep(.el-textarea__wrapper),
:deep(.el-select .el-input__wrapper),
:deep(.el-button),
.avatar-uploader .el-upload,
.el-icon.avatar-uploader-icon {
    border-radius: 0;
}

/* 移除下拉菜单的圆角 */
:deep(.el-select__popper),
:deep(.el-select-dropdown),
:deep(.el-select-dropdown__wrap) {
    border-radius: 0;
}

/* 移除标签选择器的圆角 */
:deep(.el-tag) {
    border-radius: 0;
}

/* 移除对话框本身的圆角 */
:deep(.el-dialog) {
    border-radius: 0;
}

/* 修复文本域的边框和焦点样式 */
:deep(.el-textarea .el-textarea__inner) {
    border: 1px solid var(--el-border-color);
    transition: none;
}

:deep(.el-textarea .el-textarea__inner:focus) {
    border: 1px solid var(--el-color-primary);
    box-shadow: none;
}

:deep(.el-textarea .el-textarea__wrapper) {
    padding: 0;
    box-shadow: none !important;
}

:deep(.el-textarea .el-textarea__wrapper:hover) {
    box-shadow: none !important;
}

/* 表格样式 */
.article-table {
    width: 100%;
}

:deep(.el-table) {
    width: 100% !important;
}

/* 确保卡片内容撑满 */
:deep(.el-card__body) {
    padding: 20px;
    width: 100%;
}

/* 标题列自适应宽度 */
:deep(.el-table .el-table__cell) {
    padding: 8px 0;
}
</style>